﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
/// <summary>
/// 拖拽UI的脚本,挂载到需要拖拽功能的UI上
/// </summary>
public class DragUGUI : MonoBehaviour,IBeginDragHandler,IDragHandler,IEndDragHandler {

    private Vector3 m_offset;//存储图片中心点羽鼠标点击的偏移量
    private RectTransform m_rt;//存储当前拖拽图片的recttransform组件

    public void OnBeginDrag(PointerEventData eventData)
    {
        Vector3 tWorldPos;
        RectTransformUtility.ScreenPointToWorldPointInRectangle(m_rt, eventData.position, eventData.
            pressEventCamera, out tWorldPos);
        m_offset = transform.position - tWorldPos;
        SetDraggedPosition(eventData);
    }

    public void OnDrag(PointerEventData eventData)
    {
        SetDraggedPosition(eventData);
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        SetDraggedPosition(eventData);
    }
    private void SetDraggedPosition(PointerEventData eventData)
    {
        //存储当前鼠标所在位置
        Vector3 globalMousePos;
        //UI屏幕坐标转换为世界坐标
        if (RectTransformUtility.ScreenPointToWorldPointInRectangle(m_rt, eventData.position, eventData.pressEventCamera, out globalMousePos))
        {
            //设置位置及偏移量
            m_rt.position = globalMousePos + m_offset;
        }
    }
    // Use this for initialization
    void Start () {
        m_rt = GetComponent<RectTransform>();
	}
	
	// Update is called once per frame
	void Update () {
		
	}
}
